package com.cybertron.ironhide.spider.jms.convert;

import java.io.IOException;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.log4j.Logger;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.springframework.jms.support.converter.MessageConversionException;
import org.springframework.jms.support.converter.MessageConverter;

import com.cybertron.ironhide.spider.json.JacksonObjectMapper;

public class MessageConvertForJson implements MessageConverter {

	private final static Logger logger = Logger
			.getLogger(MessageConvertForJson.class);

	private JacksonObjectMapper jacksonObjectMapper;

	@Override
	public Message toMessage(Object object, Session session)
			throws JMSException, MessageConversionException {
		TextMessage msg = session.createTextMessage();
		try {
			String json = jacksonObjectMapper.writeValueAsString(object);
			logger.info("send message ...");
			msg.setText(json);
		} catch (JsonGenerationException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return msg;
	}

	@Override
	public Object fromMessage(Message message) throws JMSException,
			MessageConversionException {
		return message;
	}

	public void setJacksonObjectMapper(JacksonObjectMapper jacksonObjectMapper) {
		this.jacksonObjectMapper = jacksonObjectMapper;
	}

}
